package com.gitee.kenewstar.migration.util;

import cn.hutool.core.collection.ListUtil;
import com.gitee.kenewstar.migration.core.MigrationCode;
import com.gitee.kenewstar.migration.core.MigrationTenantId;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author kenewstar
 */
public class ReflectUtil {

    private ReflectUtil() {}

    public static <T> List<Field> getFields(Class<T> tClass) {
        List<Field> fieldList = new ArrayList<>(ListUtil.toList(tClass.getDeclaredFields()));
        Class<? super T> superclass = tClass.getSuperclass();
        while (Objects.nonNull(superclass)) {
            fieldList.addAll(ListUtil.toList(superclass.getDeclaredFields()));
            superclass = superclass.getSuperclass();
        }
        return fieldList;
    }

    public static Field queryMigrationCode(List<Field> fieldList) {
        return queryAnnotationField(fieldList, MigrationCode.class);
    }

    public static Field queryMigrationTenantId(List<Field> fieldList) {
        return queryAnnotationField(fieldList, MigrationTenantId.class);
    }

    public static Field queryAnnotationField(List<Field> fieldList, Class<? extends Annotation> annotationClz) {
        for (Field field : fieldList) {
            final boolean flag = field.isAnnotationPresent(annotationClz);
            if (flag) {
                return field;
            }
        }
        return null;
    }

}
